package de.slothsoft.wasbinich.android.database.local;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import de.slothsoft.wasbinich.core.Picture;
import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.PictureBean;

public class SqlPictureBean implements PictureBean {

    private final SQLiteDatabase database;

    public SqlPictureBean(SqlDatabaseHelper databaseHelper) {
	this.database = databaseHelper.getWritableDatabase();
    }

    @Override
    public Picture getRandomPicture() throws DatabaseException {
	Cursor cursor = this.database.query(SqlPictureHelper.TABLE_NAME, SqlPictureHelper.COLUMNS_PICTURE_DE, null,
		null, null, null, "RANDOM()"); //$NON-NLS-1$
	cursor.moveToFirst();
	Picture result = cursorToPicture(cursor);
	cursor.close();
	return result;
    }

    private Picture cursorToPicture(Cursor cursor) {
	if (cursor.isAfterLast())
	    return null;
	int index = 1;
	return new Picture(cursor.getString(index++), cursor.getString(index++), split(cursor.getString(index++)),
		cursor.getString(index++));
    }

    private String[] split(String string) {
	return string == null ? null : string.split(","); //$NON-NLS-1$
    }
}